package com.x.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.metrics.MetricsEndpoint;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * the class of advance
 *
 * <p>
 * 通过 Spring Boot Actuator 获取 JVM 和 CPU 的性能指标。
 *
 * @author little_lunatic
 * @date 2025-03-21
 */
@RestController
@RequestMapping
public class MetricsController {

    @Autowired
    @Lazy
    private MetricsEndpoint metricsEndpoint;

    @GetMapping("/jvm")
    public Map<String, Object> getJvmMetrics() {
        Map<String, Object> metrics = new HashMap<>();
        metrics.put("jvm.memory.used", metricsEndpoint.metric("jvm.memory.used", null).getMeasurements());
        MetricsEndpoint.ListNamesResponse listNamesResponse = metricsEndpoint.listNames();
        for (String name : listNamesResponse.getNames()) {
//            System.out.println(name + metricsEndpoint.metric(name, null).getMeasurements());
            metrics.put(name, metricsEndpoint.metric(name, null).getMeasurements());
        }

        metrics.put("jvm.memory.max", metricsEndpoint.metric("jvm.memory.max", null).getMeasurements());
        return metrics;
    }

    @GetMapping("/cpu")
    public Map<String, Object> getCpuMetrics() {
        Map<String, Object> metrics = new HashMap<>();
        metrics.put("system.cpu.usage", metricsEndpoint.metric("system.cpu.usage", null).getMeasurements());
        return metrics;
    }
}